<template>
  <div class="app-container">
    <el-card>
      <div class="filter-container">
        <el-form :inline="true">
          <el-form-item label="门店">
            <el-select
              v-model="queryParams.storeId"
              placeholder="请选择门店"
              clearable
              style="width: 200px"
              @change="handleQuery"
            >
              <el-option
                v-for="item in storeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="药品">
            <el-select
              v-model="queryParams.medicineId"
              placeholder="请选择药品"
              clearable
              style="width: 200px"
              @change="handleQuery"
            >
              <el-option
                v-for="item in medicineOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
            <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain @click="handleAdd">新增</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="inventoryList">
        <el-table-column label="ID" prop="id" width="80" />
        <el-table-column label="门店" align="center" prop="storeId">
          <template #default="scope">
            {{ getStoreName(scope.row.storeId) }}
          </template>
        </el-table-column>
        <el-table-column label="药品" align="center" prop="medicineId">
          <template #default="scope">
            {{ getMedicineName(scope.row.medicineId) }}
          </template>
        </el-table-column>
        <el-table-column label="药品名称" width="150">
          <template #default="scope">
            {{ getMedicineName(scope.row.medicineId) }}
          </template>
        </el-table-column>
        <el-table-column label="当前库存数量" prop="quantity" width="120" />
        <el-table-column label="库存预警值" prop="warningQty" width="120" />
        <el-table-column label="库存状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.quantity <= scope.row.warningQty ? 'danger' : 'success'">
              {{ scope.row.quantity <= scope.row.warningQty ? '库存不足' : '库存正常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="库存更新时间" prop="updateTime" width="180" />
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加或修改对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
        <el-form ref="inventoryFormRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="门店" prop="storeId">
            <el-select v-model="form.storeId" placeholder="请选择门店" style="width: 100%">
              <el-option
                v-for="item in storeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="药品" prop="medicineId">
            <el-select v-model="form.medicineId" placeholder="请选择药品" style="width: 100%">
              <el-option
                v-for="item in medicineOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="当前库存数量" prop="quantity">
            <el-input-number v-model="form.quantity" :min="0" style="width: 100%" />
          </el-form-item>
          <el-form-item label="库存预警值" prop="warningQty">
            <el-input-number v-model="form.warningQty" :min="0" style="width: 100%" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  listInventory,
  getInventory,
  addInventory,
  updateInventory,
  delInventory
} from '@/api/inventory'
import { listMedicine } from '@/api/medicine'
import { listStore } from '@/api/store'
import { Search, Refresh } from '@element-plus/icons-vue'

// 遮罩层
const loading = ref(false)
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 查询参数
const queryParams = ref({
  storeId: undefined,
  medicineId: undefined
})

// 表单参数
const form = ref({
  id: undefined,
  storeId: undefined,
  medicineId: undefined,
  quantity: 0,
  warningQty: 0
})

// 表单校验
const rules = {
  storeId: [{ required: true, message: '门店ID不能为空', trigger: 'blur' }],
  medicineId: [{ required: true, message: '药品ID不能为空', trigger: 'blur' }],
  quantity: [{ required: true, message: '库存数量不能为空', trigger: 'blur' }],
  warningQty: [{ required: true, message: '库存预警值不能为空', trigger: 'blur' }]
}

const inventoryFormRef = ref()
const inventoryList = ref([])
// 药品选项
const medicineOptions = ref([])
// 门店选项
const storeOptions = ref([])

// 获取药品列表
const getMedicineList = async () => {
  try {
    const res = await listMedicine()
    medicineOptions.value = res || []
  } catch (error) {
    console.error('获取药品列表失败', error)
    ElMessage.error('获取药品列表失败')
  }
}

// 获取门店列表
const getStoreList = async () => {
  try {
    const res = await listStore()
    storeOptions.value = res || []
  } catch (error) {
    console.error('获取门店列表失败', error)
    ElMessage.error('获取门店列表失败')
  }
}

// 组件挂载时获取药品和门店数据
onMounted(() => {
  getMedicineList()
  getStoreList()
  getList()
})

// 获取药品名称
const getMedicineName = (medicineId) => {
  const medicine = medicineOptions.value.find((item) => item.id === medicineId)
  return medicine ? medicine.name : medicineId
}

// 获取门店名称
const getStoreName = (storeId) => {
  const store = storeOptions.value.find((item) => item.id === storeId)
  return store ? store.name : storeId
}

/** 查询库存列表 */
const getList = async () => {
  loading.value = true
  try {
    const res = await listInventory(queryParams.value)
    inventoryList.value = res
    loading.value = false
  } catch (error) {
    loading.value = false
    console.error(error)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    storeId: undefined,
    medicineId: undefined
  }
  handleQuery()
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加库存信息'
}

/** 修改按钮操作 */
const handleUpdate = (row) => {
  reset()
  const id = row.id || row.medicineId
  getInventory(id).then((response) => {
    Object.assign(form.value, response)
    open.value = true
    title.value = '修改库存信息'
  })
}

/** 提交按钮 */
const submitForm = () => {
  inventoryFormRef.value.validate((valid) => {
    if (valid) {
      if (form.value.id) {
        updateInventory(form.value).then((response) => {
          ElMessage.success('修改成功')
          open.value = false
          getList()
        })
      } else {
        addInventory(form.value).then((response) => {
          ElMessage.success('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
const handleDelete = (row) => {
  const id = row.id || row.medicineId
  ElMessageBox.confirm('是否确认删除该库存信息?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(function () {
      return delInventory(id)
    })
    .then(() => {
      getList()
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}

/** 表单重置 */
const reset = () => {
  form.value = {
    id: undefined,
    storeId: undefined,
    medicineId: undefined,
    quantity: 0,
    warningQty: 0
  }
}

/** 取消按钮 */
const cancel = () => {
  open.value = false
  reset()
}

onMounted(() => {
  getList()
  getMedicineList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.filter-container {
  padding-bottom: 10px;
}
.mb8 {
  margin-bottom: 8px;
}
</style>
